package com.leezt.designpattern.creation.s01singleton;

import java.util.concurrent.atomic.AtomicLong;

/*
 * implement ID generator with lazy way and double check. And its implementation is thread safe.
 */
public class DoubleCheckIdGenerator {
    private final AtomicLong id = new AtomicLong(0);
    // volatile is used to prevent instructions reorder
    private static volatile DoubleCheckIdGenerator instance;
    private DoubleCheckIdGenerator(){}
    public static DoubleCheckIdGenerator getInstance() {
        if (null == instance) {
            synchronized (DoubleCheckIdGenerator.class) {
                if (null == instance) {
                    instance = new DoubleCheckIdGenerator();
                }
            }
        }
        return instance;
    }

    public long getId() {
        return id.incrementAndGet();
    }
}
